package com.snj.visangedu;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.nhn.android.naverlogin.OAuthLogin;
import com.nhn.android.naverlogin.OAuthLoginHandler;
import com.nhn.android.naverlogin.data.OAuthLoginState;
import com.snj.visangedu.drm.DRMINFO;
import com.snj.visangedu.lib.CustomHttpClient;
import com.snj.visangedu.lib.Global;
import com.snj.visangedu.lib.NewsLib;

public class EntryActivity extends Activity implements OnClickListener {
	
	
	
	String tag = "MainActivity";
	
	double version = 0;
	
	/** 
	 * client
	 */
	private static String OAUTH_CLIENT_ID = "mnoLX2JJmdBpyKHYEIHB";
	private static String OAUTH_CLIENT_SECRET = "UPRdbZYXot";
	private static String OAUTH_CLIENT_NAME = "占쎈뮞占쎄숲占쎈탵�뀎占�";
	private static String OAUTH_CALLBACK_INTENT = "com.snj.visangedu";	
	
	private static OAuthLogin mOAuthLoginInstance;
	private static Context mContext;
	
	DRMINFO _info = DRMINFO.getInstance();
	
	RelativeLayout rlly_popup = null;
	ImageView img_network = null; 
	
	
	AlertDialog alertCardApp = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_intro);
		
		Global.pref = getSharedPreferences(Global.pkgname, 0);
		
		mContext = this;
		
		Global.loadedimgcount = 0;
		
		Global.typeface1 = Typeface.createFromAsset(getAssets(), Global.TYPEFACE_1_NAME);
	    Global.typeface2 = Typeface.createFromAsset(getAssets(), Global.TYPEFACE_2_NAME);
	    
	    img_network = (ImageView)findViewById(R.id.img_popup_network);

	    
	    rlly_popup = (RelativeLayout)findViewById(R.id.rlly_popup);
	    if(!Global.isNetworkStat(mContext))
	    {
	    	rlly_popup.setVisibility(View.VISIBLE);

	    	img_network.setVisibility(View.VISIBLE);
	    	new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					EntryActivity.this.finish();
					
				}
			}, 5000);
	    	
	    	return;
	    }
		
		registGCM();
		
		try 
		{
			PackageInfo i = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
			version = Double.parseDouble(i.versionName);
			
		}
		catch(NameNotFoundException e) 
		{
			
		}
			
		Log.d(tag, "버전 : " + version);
		 
		
		
		new AsyncTask<String, String, String>()
		{
			double server_version = 0;
			
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				
				ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair("apptype", "A"));
				
            	String result = "";
            	JSONObject resultobject = null;
            	
            	try {
            		NewsLib.InitNews();
            		
            		Log.d(tag, "Connect to " + Global.versionurl);
					//result = CustomHttpClient.executeHttpPost(Global.versionurl, postParameters);
					result = CustomHttpClient.executeHttpGet(Global.versionurl);//, postParameters);
					//CustomHttpClient.executeHttpPostImage($url, postParameters)
					Log.d("EntryActivity", result);
					
			 		resultobject = new JSONObject(result);
					
					if(resultobject.getString("result").equals("success"))
					{
						server_version = resultobject.getDouble("version");
						
						if(server_version > version)
						{
							return "update";
						}
						else
						{
							return null;
						}
					}
					else
					{
						return "fail";
						//return null;
					}
					
            	}
            	catch(Exception e)
            	{
            		
            	}
            	
            	return "fail";
            	//return null;
			}
			
			

			@Override
			protected void onProgressUpdate(String... values) {
				// TODO Auto-generated method stub
				super.onProgressUpdate(values);
				
				Log.d(tag, "value : " + values[0]);
				if(values[0].equals("show"))
				{
					rlly_popup.setVisibility(View.VISIBLE);
			    	
			    	img_network.setVisibility(View.GONE);
				}
				else if(values[0].equals("hide"))
				{
					rlly_popup.setVisibility(View.GONE);
				}
			}



			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				
				if(result != null)
				{
					if(result.equals("fail"))
					{
						Toast.makeText(EntryActivity.this, "버전 정보를 불러오는데 실패했습니다.", Toast.LENGTH_LONG).show();
						finish();
						
						return;
					} 
					else if(result.equals("update"))
					{
						alertCardApp =  new AlertDialog.Builder(EntryActivity.this) 
				  		.setIcon(android.R.drawable.ic_dialog_info) 
				  		.setTitle("업데이트 알림") 
				  		.setMessage("스터디뷰가 " + server_version + "버전으로 업데이트 되었습니다. \n 지금 업데이트 하시겠습니까?") 
				  		.setPositiveButton("업데이트", new DialogInterface.OnClickListener() { 
				            @Override 
				            public void onClick(DialogInterface dialog, int which) { 
				            	Intent intent = new Intent(Intent.ACTION_VIEW);
				            	intent.setData(Uri.parse("market://details?id=com.snj.visangedu"));
				            	startActivity(intent);				            	
				            	finish();
				            } 
				  		}) 
				  		.setNegativeButton("취소", new DialogInterface.OnClickListener() { 			 
				            @Override 
				            public void onClick(DialogInterface dialog, int which) { 
				            	 
				            	finish(); 
				            } 
				  		})
				  		.create();
						
						alertCardApp.show();
						//finish();
						
						return;
					}
				}
				else
				{
					Log.d(tag, "정상 버전");
					//finish();
				}
				
				
				Log.d(tag, "네이버 로그인 초기화");
				initData();				
				
				
				if(mOAuthLoginInstance.getState(mContext) != OAuthLoginState.OK)
				{
					Log.d(tag, "로그인  안됨");
					mOAuthLoginInstance.startOauthLoginActivity(EntryActivity.this, mOAuthLoginHandler);
				}
				else
				{
					
					new AsyncTask<String, String, String>()
					{

						@Override
						protected String doInBackground(String... params) {
							// TODO Auto-generated method stub
							
							String url = "https://apis.naver.com/nidlogin/nid/getUserProfile.xml";
							String at = mOAuthLoginInstance.getAccessToken(mContext);
							String result = mOAuthLoginInstance.requestApi(mContext, at, url);
							Log.d("MainActivity", "hash : " + result);
							
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							TelephonyManager systemService = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
							Global.phone = systemService.getLine1Number();
							
							if(Global.phone != null)
							{
								if(Global.phone.length() >= 10)
								{
									Global.phone = Global.phone.substring(Global.phone.length()-10,Global.phone.length());
									Global.phone="0"+Global.phone;
								}
								
								Log.d("MainActivity", "Phone : " + Global.phone);
							}
							else
							{
								Global.phone = "";
							}
							
							Log.d("MainActivity", "Naver id : " + result);
							
							result = result.substring(result.indexOf("<email>") + 7);
							result = result.substring(result.indexOf("![CDATA[") + 8);
							
							result = result.substring(0, result.indexOf("@"));
							
							Global.naverid = result;
							Log.d("MainActivity", "Naver id : " + Global.naverid);
							
							ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
							postParameters.add(new BasicNameValuePair("os", "A"));
							postParameters.add(new BasicNameValuePair("phone", Global.phone));
							postParameters.add(new BasicNameValuePair("devicekey", Global.devicekey));
							postParameters.add(new BasicNameValuePair("naverid", result));
							
			            	result = "";
			            	JSONObject resultobject = null;
			            	
			            	try {
								result = CustomHttpClient.executeHttpPost(Global.memberurl, postParameters);
								Log.d("MainActivity", result);
								
								Log.d("MainActivity", "Path : " + Global.ex_storage);
								
						 		resultobject = new JSONObject(result);
								
								if(!resultobject.getString("result").equals("success"))
								{
									Log.d("MainActivity", "Fail");
									return null;
								}
								
								
								Global.ispaid = Boolean.valueOf(resultobject.getString("ispaid").equals("1") ? "true" : "false");
								Global.level = resultobject.getInt("level");
								
								Global.ismonthly = Boolean.valueOf(resultobject.getString("ismonthly").equals("1") ? "true" : "false");
								
								Log.d("MainActivity", "ispaid : " + Global.ispaid + ", ismonthly : " + Global.ismonthly);
			            	}
			            	catch(Exception e)
			            	{
			            		
			            	}
							
			            	Log.d(tag, "InitNews");
							
							return result;
						}

						@Override
						protected void onPostExecute(String result) {
							// TODO Auto-generated method stub
							super.onPostExecute(result);
							
							mContext.startActivity(new Intent(mContext, HomeActivity.class));
							//mContext.startActivity(new Intent(mContext, CalendarSample.class));
							//mContext.startActivity(new Intent(mContext, VideoAct.class));
							//finish();
						}
						
						
						
					}.execute(Global.phone, Global.devicekey);
					
				}
			}
			
			
			
		}.execute(Global.phone, Global.devicekey);
		
	}
	
	private void initData() {
		mOAuthLoginInstance = OAuthLogin.getInstance();
		mOAuthLoginInstance.init(mContext, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_CLIENT_NAME, OAUTH_CALLBACK_INTENT);
	}
	
	
	 
	/**
	 * startOAuthLoginActivity()  
	 */
	static private OAuthLoginHandler mOAuthLoginHandler = new OAuthLoginHandler() {
		@Override
		public void run(boolean success) {
			
			Log.d("MainActivity", "result : " + success);
			if (success) {
				String accessToken = mOAuthLoginInstance.getAccessToken(mContext);
				String refreshToken = mOAuthLoginInstance.getRefreshToken(mContext);
				long expiresAt = mOAuthLoginInstance.getExpiresAt(mContext);
				String tokenType = mOAuthLoginInstance.getTokenType(mContext);
				
				Log.d("MainActivity", "success");
				
				new AsyncTask<String, String, String>()
				{

					@Override
					protected String doInBackground(String... params) {
						// TODO Auto-generated method stub
						
						String url = "https://apis.naver.com/nidlogin/nid/getUserProfile.xml";
						String at = mOAuthLoginInstance.getAccessToken(mContext);
						String result = mOAuthLoginInstance.requestApi(mContext, at, url);
						Log.d("MainActivity", "hash : " + result);
						
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						TelephonyManager systemService = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
						Global.phone = systemService.getLine1Number();
						
						if(Global.phone != null)
						{
							if(Global.phone.length() >= 10)
							{
								Global.phone = Global.phone.substring(Global.phone.length()-10,Global.phone.length());
								Global.phone="0"+Global.phone;
							}
							
							Log.d("MainActivity", "Phone : " + Global.phone);
						}
						else
						{
							Global.phone = "";
						}
						
						Log.d("MainActivity", "Naver id : " + result);
						
						result = result.substring(result.indexOf("<email>") + 7);
						result = result.substring(result.indexOf("![CDATA[") + 8);
						
						result = result.substring(0, result.indexOf("@"));
						
						Global.naverid = result;
						
						ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
						postParameters.add(new BasicNameValuePair("os", "A"));
						postParameters.add(new BasicNameValuePair("phone", Global.phone));
						postParameters.add(new BasicNameValuePair("devicekey", Global.devicekey));
						postParameters.add(new BasicNameValuePair("naverid", Global.naverid));
						
						Log.d("MainActivity", "param : " + postParameters.toString());
						 
		            	result = "";
		            	JSONObject resultobject = null;
		            	
		            	try {
							result = CustomHttpClient.executeHttpPost(Global.memberurl, postParameters);
							Log.d("MainActivity", result);
							 
							Log.d("MainActivity", "Path : " + Global.ex_storage);
							
							resultobject = new JSONObject(result);
							
							if(!resultobject.getString("result").equals("success"))
							{
								Log.d("MainActivity", "Fail");
								return null;
							}
							
							
							Global.ispaid = Boolean.valueOf(resultobject.getString("ispaid").equals("1") ? "true" : "false");
							Global.ismonthly = Boolean.valueOf(resultobject.getString("ismonthly").equals("1") ? "true" : "false");
							Global.level = resultobject.getInt("level"); 
							Log.d("MainActivity", "ispaid : " + Global.ispaid + ", ismonthly : " + Global.ismonthly);
		            	}
		            	catch(Exception e)
		            	{
		            		
		            	}
						
						//NewsLib.InitNews();
						return result;
					}

					@Override
					protected void onPostExecute(String result) {
						// TODO Auto-generated method stub
						super.onPostExecute(result);
						
						
					}
					
					
					
				}.execute(Global.phone, Global.devicekey);
				
				mContext.startActivity(new Intent(mContext, HomeActivity.class));
				
			} else {
				String errorCode = mOAuthLoginInstance.getLastErrorCode(mContext).getCode();
				String errorDesc = mOAuthLoginInstance.getLastErrorDesc(mContext);
				Toast.makeText(mContext, "errorCode:" + errorCode + ", errorDesc:" + errorDesc, Toast.LENGTH_SHORT).show();
				Log.d("MainActivity", "errorCode:" + errorCode + ", errorDesc:" + errorDesc);
				//mOAuthLoginInstance.get
				
				((EntryActivity)mContext).finish();
			}
			
			
			//mContext.startActivity(new Intent(mContext, CalendarSample.class));	
			((EntryActivity)mContext).finish();
		};
	};
	
	

	private void registGCM() {
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);

		String regId = GCMRegistrar.getRegistrationId(this);
		Log.d(tag, String.format("reg ID : %s", regId));

		if (regId.equals("") == true) {
			GCMRegistrar.register(this, GCMIntentService.SEND_ID);
			Global.devicekey = GCMRegistrar.getRegistrationId(this);
			Log.d(tag, String.format("new created key : %s", Global.devicekey));
		} else {
			Global.devicekey = regId;
			Log.d(tag, String.format("key : %s", Global.devicekey));
		}

		// APP_DEVICE_KEY
		SharedPreferences pref = getSharedPreferences("Setting", 0);
		SharedPreferences.Editor edit = pref.edit();
		edit.putString("APP_DEVICE_KEY", Global.devicekey);
		edit.commit();
	}

	@SuppressWarnings("unused")
	private void unregistGCM() {
		if (GCMRegistrar.isRegistered(this)) {
			GCMRegistrar.unregister(this);

			// APP_DEVICE_KEY 
			SharedPreferences pref = getSharedPreferences("Setting", 0);
			SharedPreferences.Editor edit = pref.edit();
			edit.putString("APP_DEVICE_KEY", "");
			edit.commit();
		}
	}
	
		
	public void ScreenInfo() {
	    DisplayMetrics displayMetrics = new DisplayMetrics();

	    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

	    Global.deviceWidth = displayMetrics.widthPixels;

	    Global.deviceHeight = displayMetrics.heightPixels;

	    Log.d(tag, "deviceWidth=" + Global.deviceWidth + " , deviceHeight=" + Global.deviceHeight);

	    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

	    Global.dipWidth = (int) (120 * displayMetrics.density);

	    Global.dipHeight = (int) (90 * displayMetrics.density);

	    Log.d(tag, "dipWidth=" + Global.dipWidth + " , dipHeight=" + Global.dipHeight);
	  }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if(v.getId() == R.id.imgbtn_x)
		{
			finish();
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		if(alertCardApp != null)
		{
			alertCardApp.dismiss();
		}
	}
	
	
}
